<?php
/**
 * alltosun.com 微信退款控制器 index.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址:   http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 勾国印 (gougy@alltosun.com) $
 * $Date: 2015-5-5 下午6:26:49 $
 * $Id$
*/
//此控制器适应于微信支付V3版本，不适用于V2版本
error_reporting(0);
if(ONDEV) {
    include MODULE_PATH."/openapi/config/weixindev_config.php";
} else {
    include MODULE_PATH."/openapi/config/weixin_config.php";
}
include MODULE_PATH."/openapi/helper/WxPayPubHelper/WxPayPubHelper.php";

//扫码支付
include MODULE_PATH."/openapi/helper/WxpayAPI_v3/lib/WxPay.Api.php";
include MODULE_PATH."/openapi/helper/WxpayAPI_v3/WxPay.NativePay.php";

class Action
{
    // 微信公众号身份的唯一标识。审核通过后，在微信发送的邮件中查看
    private $wx_appid;

    // 受理商ID，身份标识
    private $wx_mchid;

    // 商户支付密钥Key。审核通过后，在微信发送的邮件中查看
    private $wx_key;

    // JSAPI接口中获取openid，审核后在公众平台开启开发模式后可查看
    private $wx_appsecret;

    // 获取access_token过程中的跳转uri，通过跳转将code传入jsapi支付页面 此处没有用到
    private $wx_js_api_call_url;

    // 证书路径,注意应该填写绝对路径
    private $apiclient_cert;
    private $apiclient_key;

    // 异步通知url设置
    private $wx_notify_url;

    // 退款请求接口
    private $url;

    // curl超时设置
    private $wx_curl_timeout;

    public function __construct()
    {
        $this->wx_appid           = WxPayConf_pub::APPID;
        $this->wx_mchid           = WxPayConf_pub::MCHID;
        $this->wx_key             = WxPayConf_pub::KEY;
        $this->wx_appsecret       = WxPayConf_pub::APPSECRET;
        $this->wx_js_api_call_url = WxPayConf_pub::JS_API_CALL_URL;
        $this->wx_notify_url      = WxPayConf_pub::NOTIFY_URL;
        if(ONDEV) {
            //获取证书的绝对路径
            $this->apiclient_cert    = MODULE_PATH . '/openapi/helper/WxPayPubHelper/cacert_dev/apiclient_cert.pem';
            $this->apiclient_key     = MODULE_PATH . '/openapi/helper/WxPayPubHelper/cacert_dev/apiclient_key.pem';
        } else {
            //获取证书的绝对路径
            $this->apiclient_cert    = MODULE_PATH . '/openapi/helper/WxPayPubHelper/cacert/apiclient_cert.pem';
            $this->apiclient_key     = MODULE_PATH . '/openapi/helper/WxPayPubHelper/cacert/apiclient_key.pem';
        }

        //退款请求接口
        $this->url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
        //接口请求超时时间
        $this->wx_curl_timeout    = WxPayConf_pub::CURL_TIMEOUT;
    }

    public function __call($action = '', $param = array())
    {
         // 退货单ID
         $refund_id = Request::getParam('refund_id', 0);

         $remark = '无';

        if (!$refund_id) {
            exit('退款失败，退款单号错误');
        }

        $refund_info = _uri('refund', $refund_id);
        if (!$refund_info || $refund_info['status'] == 0) {
            exit('退款失败，没有此退货单信息');
        }

        if (!in_array($refund_info['refund_status'], array(5,15))) {
            exit('该工单不处于可退款状态');
        }

//         if ($refund_info['refund_pay_status'] == 1) {
//             return '该退款信息正在处理中';
//         } elseif($refund_info['refund_pay_status'] == 2) {
//             return '该退款信息已处理成功';
//         }

        $order_info = _uri('order', $refund_info['order_id']);
        if (!$order_info || !$order_info['transaction_id']) {
            exit('退款失败，对应的订单不存在');
        }
        $pay_time = date('YmdH', strtotime($order_info['pay_time']));
        if($order_info['origin'] == 'm') {
            $is_num = 2;
        } else {
            $is_num = 1;
        }
        $out_trade_no = $pay_time.$is_num.$order_info['id'];
        $out_refund_no = $refund_info['id'];
        $transaction_id = $order_info['transaction_id'];

        $remark = $remark;

        if(ONDEV){
            $total_fee = 1;
        }else{
            $total_fee = $order_info['price'] * 100;
        }

        $refund_fee = '';
        $refund_coupon_price = 0;
        $refund_relation_list = _model('refund_relation')->getList(array('refund_id'=>$refund_info['id'], 'status'=>1));
        foreach ($refund_relation_list as $v) {
            $refund_fee += ($v['refund_num'] * $v['real_price']);
        }

        if(ONDEV){
            $refund_fee = 1;
        }else{
            $refund_fee = $refund_info['real_price']*100;
        }

        $info = array(
            'out_trade_no' => $out_trade_no,
            'transaction_id' => $transaction_id,
            'total_fee' => $total_fee,
            'refund_fee' => $refund_fee,
            //'out_refund_no' => WxPayConf_pub::MCHID.date("YmdHis"),
            'out_refund_no' => $out_refund_no,
            'op_user_id' => WxPayConf_pub::MCHID
        );

        exit($this->refund($info));

    }

    //退款操作
    public function refund($info)
    {
        $wxpayRefund = new Refund_pub();

        $wxpayRefund->setParameter("out_trade_no",$info['out_trade_no']);
        $wxpayRefund->setParameter("transaction_id",$info['transaction_id']);
        $wxpayRefund->setParameter("total_fee",$info['total_fee']);
        $wxpayRefund->setParameter("refund_fee",$info['refund_fee']);
        $wxpayRefund->setParameter("out_refund_no",$info['out_refund_no']);
        $wxpayRefund->setParameter("op_user_id",$info['op_user_id']);


        $xml = $wxpayRefund->createXml($info);

        $cert_info = array(
            'apiclient_cert' => $this->apiclient_cert,
            'apiclient_key' => $this->apiclient_key
        );

        $postXml = $wxpayRefund->postXmlSSLCurl($xml, $this->url, $cert_info, $this->wx_curl_timeout);

        //$postXml = $this->postXmlCurl($xml, $this->url, true, $this->wx_curl_timeout);
        // mail_helper::mail('353182225@qq.com', '微信退款$postXml信息', var_export($postXml, true));
        $result = $wxpayRefund->xmlToArray($postXml);

        // mail_helper::mail('353182225@qq.com', '微信退款传参信息', var_export($info, true));
        // mail_helper::mail('353182225@qq.com', '微信退款xmlToArray信息', var_export($result, true));

        $order_id = $info['out_trade_no'];
        $order_id = substr($order_id, 11);
        //获取退货单id
        // mail_helper::mail('353182225@qq.com', '获取退货单id', $order_id);
        //$refund_info = _uri('refund', array('order_id' => $order_id, 'refund_status <>' => 20));
        $refund_id = $result['out_refund_no'];
         // mail_helper::mail('353182225@qq.com', '退款单id数字', $refund_id);
//         mail_helper::mail('245629560@qq.com', '退款单id数组', var_export($refund_id, true));
         // mail_helper::mail('353182225@qq.com', '退款单信息', var_export($refund_info, true));

        //入库微信退款记录
        $transaction_id       = $result['transaction_id']?$result['transaction_id']:'';
        $transaction_refund_id = $result['refund_id']?$result['refund_id']:0;
        $total_fee             = $result['total_fee']?$result['total_fee']:'0';
        $refund_fee            = $result['refund_fee']?$result['refund_fee']:'0';
        $refund_status         = $result['result_code']?$result['result_code']:'';

        $refund_log_info = array(
            'order_id' => $order_id,
            'refund_id' => $refund_id,
            'transaction_id' => $transaction_id,
            'transaction_refund_id' => $transaction_refund_id,
            'total_fee' => $total_fee,
            'refund_fee' => $refund_fee,
            'refund_status' => $refund_status
        );

        // mail_helper::mail('353182225@qq.com', '微信退款记录信息', var_export($refund_log_info, true));
        _model('wx_refund_log')->create($refund_log_info);
        // mail_helper::mail('353182225@qq.com', '微信退款记录信息', var_export($refund_log_info, true));
        if($result['return_code'] == 'SUCCESS'){
            //更新退款单状态为退款成功（20）
            _model('refund')->update(array('id' => $refund_id), array('refund_status' => 20, 'transaction_id' => $transaction_refund_id, 'refunded_time'=>date('Y-m-d H:i:s')));
            //更新订单状态为已取消（0）
            _model('order')->update(array('id' => $order_id), array('progress' => 20));
            //返还销量
            order_helper::refund_sale_num($order_id);
            //返回库存
            order_helper::refund_stock($order_id);

            $info = _widget('erp_lenovo.erp_lenovo_order')->AddREOrder($refund_id);

            exit('ok');
        }else{
            //更新退款单状态为退款失败（23）
            _model('refund')->update(array('id' => $refund_id), array('refund_status' => 23));
            exit('微信退款失败，'. $result['err_code_des']);
        }

    }

}
?>